package com.healthcarex.hip.saas.security.service.impl;

import com.healthcarex.hip.saas.common.exception.BusinessException;
import com.healthcarex.hip.saas.common.model.BaseModel;
import com.healthcarex.hip.saas.mybatis.service.impl.BaseServiceImpl;
import com.healthcarex.hip.saas.security.dao.ResourceDao;
import com.healthcarex.hip.saas.security.model.SysApp;
import com.healthcarex.hip.saas.security.model.SysResource;
import com.healthcarex.hip.saas.security.model.SysRole;
import com.healthcarex.hip.saas.security.service.ISysAppService;
import com.healthcarex.hip.saas.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author  ChenPan
 * @date   2018/7/31 16:37
 * description:
 */
@Service
public class SysAppServiceImpl extends BaseServiceImpl<SysApp> implements ISysAppService {

    @Autowired
    private ResourceDao resourceDao;


    @Override
    public List<SysApp> findSysApp(SysApp app) {
        Example example = new Example(SysApp.class);
        if ((StringUtils.isNotBlank(app.getAppName()))) {
            example.createCriteria().andCondition("app_name=", app.getAppName());
        }
        if ((StringUtils.isNotBlank(app.getAppEnName()))) {
            example.createCriteria().andCondition("app_en_name=", app.getAppEnName());
        }
        if ((StringUtils.isNotBlank(app.getAppAbbr()))) {
            example.createCriteria().andCondition("app_abbr=", app.getAppAbbr());
        }
        example.setOrderByClause("create_time");
        return this.selectByExample(example);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysApp(SysApp app) {
        app.setId(this.getSequence(BaseModel.BASE_SEQ));
        app.setCreateBy(SecurityUtils.getUsername());
        app.setCreateTime(new Date());

        this.save(app);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysApp(SysApp app) {
        app.setUpdateBy(SecurityUtils.getUsername());
        app.setUpdateTime(new Date());

        this.updateNotNull(app);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysApp(String appIds) {

        // 在资源中存在的应用不能删除
        Example example = new Example(SysResource.class);
        example.createCriteria().andIn("appId", Arrays.asList(appIds.split(",")));

        if (resourceDao.selectCountByExample(example) > 0) {
            throw new BusinessException("系统中存在当前需要删除的应用的资源，不允许删除");
        } else {
            List<String> list = Arrays.asList(appIds.split(","));
            this.batchDelete(list, "id", SysApp.class);
        }
    }
}
